import { NodePoint } from "@/utils/antvx6/nodePoint";
import { edgeLabels, edgeAttrs, edgeRouter } from "@/utils/antvx6/configurationDetails";
import { NodeData, GraphData } from "@/utils/antvx6/extractNodesAndEdges";
import { computedSize } from "@/utils/antvx6/drawArea";

/**
 * 将节点遍历到画布上
 * @param { GraphData }  graphObj
 * @param { HTMLElement } elementGraph
 */
export const renderData = (elementGraph: any, graphObj: GraphData) => {
  const addNodeList: any[] = [];
  const nodes = graphObj?.nodes || [];
  nodes.forEach((item: NodeData) => {
    if (item.shape === "node-point") {
      const nodeP = new NodePoint();
      nodeP.setData({
        id: item.id,
        shape: item.shape,
        x: item.dataStorage.x,
        y: item.dataStorage.y,
        data: item.dataStorage,
      });
      addNodeList.push(nodeP.getModel());
    } else if (item.shape === "node-area") {
      const points = item.dataStorage.points;
      const size = computedSize(points);
      addNodeList.push({
        id: item.id,
        shape: item.shape,
        zIndex: -1,
        width: size.width,
        height: size.height,
        x: item.dataStorage.points[0].x,
        y: item.dataStorage.points[0].y,
        data: item.dataStorage,
      });
    }
  });
  // 渲染节点
  elementGraph?.addNodes(addNodeList);
  // 判断
  if (addNodeList.length === nodes.length) {
    setEdges(elementGraph, graphObj.edges);
  }
};

/**
 * 将边遍历到画布上
 * @param { Array }  edges
 * @param { HTMLElement } elementGraph
 */
const setEdges = (elementGraph: any, edges: any[]) => {
  const addEdgeList: any[] = [];
  edges.forEach((item) => {
    const param = {
      id: item.id,
      source: {
        cell: item.startNodeId,
      },
      target: {
        cell: item.endNodeId,
      },
      zIndex: 0,
      data: item.dataStorage,
      shape: item.shape,
      labels: edgeLabels(item.id),
      router: edgeRouter(item.dataStorage.edgeType),
      attrs: edgeAttrs(2, item.dataStorage.lineMode),
    };
    addEdgeList.push(param);
  });
  elementGraph?.addEdges(addEdgeList);
};
